package com.yl.order.helper;

import android.text.TextUtils;

import com.jeremyliao.liveeventbus.LiveEventBus;
import com.net.yl.ApiRepository;
import com.net.yl.entity.ResponseEntity;
import com.net.yl.entity.SyncCategoryEntity;
import com.net.yl.entity.SyncDataProductEntity;
import com.net.yl.entity.SyncFormulaDetailEntity;
import com.net.yl.entity.SyncFormulaEntity;
import com.net.yl.entity.SyncMaterialEntity;
import com.net.yl.entity.SyncProductEntity;
import com.net.yl.entity.SyncSpecEntity;
import com.yl.order.App;
import com.yl.order.BuildConfig;
import com.yl.order.Constants;
import com.yl.order.db.entity.CategoryEntity;
import com.yl.order.db.entity.GoodsEntity;
import com.yl.order.db.entity.ProductEntity;
import com.yl.order.db.entity.SpecEntity;
import com.yl.order.entity.SyncDeviceWrap;
import com.yl.order.model.ConfigModel;
import com.yl.order.model.SyncModel;
import com.yl.order.utils.SPUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

/**
 * create by cjx on 2024/7/16
 * desc:
 */
public class DataSyncHelper {

    private final String SP_DATA_SYNC_PRODUCT = "SP_DATA_SYNC_PRODUCT_1_3_5";

    static final class HelderHolder {
        static final DataSyncHelper helper = new DataSyncHelper();
    }

    private DataSyncHelper() {

    }

    public static DataSyncHelper getInstance() {
        return HelderHolder.helper;
    }

    public void resetSn() {
        SPUtils.removeTag(SP_DATA_SYNC_PRODUCT);
    }

    public void resetProductCache() {
        SPUtils.removeTag(SP_DATA_SYNC_PRODUCT);
    }

    public void syncProductCheck() {
        boolean hasSync = SPUtils.getBoolean(SP_DATA_SYNC_PRODUCT, false);
        if (hasSync) {
            LiveEventBus.get(Constants.BUS_SYNC_PRODUCT_RESPONSE).post(new ResponseEntity<>(true, null, null));
            return;
        }
        syncProduct();
    }

    private void syncProduct() {
        ApiRepository.getInstance().syncProduct(response -> {
            if (response.success) {
                SyncDataProductEntity data = response.data;
                App.app.storeInfo = data.getStore();
                App.app.favicon = data.getFavicon();
                ConfigModel.saveDeviceWrap(new SyncDeviceWrap(App.app.activateInfo, App.app.storeInfo, App.app.favicon));
                if (initProduct(data)) {
                    LiveEventBus.get(Constants.BUS_SYNC_PRODUCT_RESPONSE)
                            .post(new ResponseEntity<>(true, null, null));
                    SPUtils.putBoolean(SP_DATA_SYNC_PRODUCT, true);
                    return;
                }
            }
            LiveEventBus.get(Constants.BUS_SYNC_PRODUCT_RESPONSE)
                    .post(new ResponseEntity<>(false, null, response.getMessage()));
        }, throwable -> LiveEventBus.get(Constants.BUS_SYNC_PRODUCT_RESPONSE)
                .post(new ResponseEntity<>(false, null, throwable.getMessage())));
    }

    private boolean initProduct(SyncDataProductEntity data) {
        ArrayList<SyncMaterialEntity> materialInfoList = data.getMaterialInfoList();
        if (materialInfoList == null || materialInfoList.isEmpty()) {
            return false;
        }

        ArrayList<SyncFormulaDetailEntity> formulaDetailList = data.getFormulaDetailList();
        if (formulaDetailList == null || formulaDetailList.isEmpty()) {
            return false;
        }

        ArrayList<SyncFormulaEntity> syncFormulaList = data.getFormulaList();
        if (syncFormulaList == null || syncFormulaList.isEmpty()) {
            return false;
        }
        // 分类
        ArrayList<SyncCategoryEntity> syncCategoryList = data.getCategoryList();
        Collections.sort(syncCategoryList, new Comparator<SyncCategoryEntity>() {
            @Override
            public int compare(SyncCategoryEntity o1, SyncCategoryEntity o2) {
                return o1.getSorted() - o2.getSorted();
            }
        });
        ArrayList<CategoryEntity> categoryList = new ArrayList<>(syncCategoryList.size());
        HashMap<Long, Integer> categoryMap = new HashMap<>(categoryList.size());
        for (SyncCategoryEntity e : syncCategoryList) {
            CategoryEntity c = new CategoryEntity(null, e.getCategory(), null, e.getName(),
                    String.valueOf(e.getId()), e.getSorted() == null ? 0 : e.getSorted());
            categoryList.add(c);
            categoryMap.put(e.getId(), c.getSort());
        }
        SyncModel.resetCategoryList(categoryList);
        // 规格
        ArrayList<SyncSpecEntity> syncSpecList = data.getSpecList();
        ArrayList<SpecEntity> specList = new ArrayList<>(syncSpecList.size());
        for (SyncSpecEntity e : syncSpecList) {
            Integer groupSort = categoryMap.get(e.getCategoryId());
            int sort = (groupSort == null ? 0 : groupSort) * 1000 + (e.getSorted() == null ? 0 : e.getSorted());
            SpecEntity s = new SpecEntity(e.getId(), String.valueOf(e.getCategoryId()), e.getName(),
                    e.getThirdId(), sort, 0, true);
            specList.add(s);
        }
        SyncModel.resetSpecList(specList);
        // 商品
        ArrayList<SyncProductEntity> syncProductList = data.getProductList();
        ArrayList<GoodsEntity> goodsList = new ArrayList<>(syncProductList.size());
        for (SyncProductEntity p : syncProductList) {
            String icon = null;
            if (!TextUtils.isEmpty(p.getImage())) {
                icon = BuildConfig.IMAGE_URL + p.getImage().replace("\\", "/");
            }
            Integer groupSort = categoryMap.get(p.getCategoryId());
            int sort = (groupSort == null ? 0 : groupSort) * 1000 + (p.getSorted() == null ? 0 : p.getSorted());
            GoodsEntity g = new GoodsEntity(null, p.getId(), String.valueOf(p.getCategoryId()), p.getName(),
                    p.getThirdId(), icon, sort, "0");
            goodsList.add(g);
        }
        SyncModel.resetGoodsList(goodsList);
        // 配方
        HashMap<Long, SyncProductEntity> goodsNumberMap = new HashMap<>(syncProductList.size());
        for (SyncProductEntity p : syncProductList) {
            goodsNumberMap.put(p.getId(), p);
        }
        HashMap<Long, SyncSpecEntity> specNumberMap = new HashMap<>(data.getSpecList().size());
        for(SyncSpecEntity s : data.getSpecList()){
            specNumberMap.put(s.getId(), s);
        }
        ArrayList<ProductEntity> productList = new ArrayList<>(syncFormulaList.size());
        for(SyncFormulaEntity f : syncFormulaList){
            SyncProductEntity product = goodsNumberMap.get(f.getProductId());
            String[] split = f.getIdentityCode().split(",");
            StringBuilder specNumber = new StringBuilder();
            StringBuilder specName = new StringBuilder();
            for (String s : split) {
                SyncSpecEntity spec = specNumberMap.get(Long.parseLong(s));
                if (spec != null) {
                    specNumber.append(",").append(spec.getThirdId() == null ? spec.getName() : spec.getThirdId());
                    specName.append("-").append(spec.getName());
                }
            }
            String goodsName;
            String goodsNumber;
            if (product != null) {
                goodsNumber = product.getThirdId() == null ? product.getName() : product.getThirdId();
                goodsName = product.getName();
            } else {
                goodsNumber = null;
                goodsName = null;
            }
            productList.add(new ProductEntity(null, goodsName, goodsNumber,
                    specNumber.substring(1), specName.substring(1), f.getThirdId(), f.getPrice(), f.isDefaultSelect(), 0));
        }
        SyncModel.resetProductList(productList);
        return true;
    }

}
